import 'package:cached_network_image/cached_network_image.dart';
import 'package:easydubbing/utils/FutureDioToken.dart';
import 'package:easydubbing/utils/SpUtil.dart';
import 'package:easydubbing/utils/api.dart';
import 'package:easydubbing/utils/style.dart';
import 'package:easydubbing/views/indexViews.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:inview_notifier_list/inview_notifier_list.dart';
import 'package:loading_indicator_view/loading_indicator_view.dart';

class IndexPage extends StatefulWidget{
  final bool isIndex;

  const IndexPage({Key key, this.isIndex}) : super(key: key);
  _IndexPageState createState() => _IndexPageState();
}
class _IndexPageState extends State<IndexPage> with TickerProviderStateMixin{

  bool isFirstIn = true;
  TabController _tabController;
  List<String> imageList = [
    "https://i0.hdslb.com/bfs/article/299700a21c88a26e4b29ce65e2eaf76223eb42d8.jpg@1320w_596h.webp",
    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2F01%2Fe5%2Fa2%2F01e5a2fda1467dcc2554100d45d8889e.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623993974&t=03971271f85bc1724a5a426728c0cccc",
    "https://i0.hdslb.com/bfs/article/538e9855dcad9ceb05da19a5b4a9b60f3f2c60f0.jpg@1320w_594h.webp"
  ];
  Future loadIndexData;
  List indexData = [];
  ScrollController _scrollController;
  bool isDragging =false;
  bool reachTop = false;
  bool isLoading = false;

  @override
  void initState() {
    _scrollController = new ScrollController(initialScrollOffset: 60);
    _scrollController.addListener(() {
      if(_scrollController.offset == 0){
        setState(() {
          reachTop = true;
        });
      }else if(reachTop == true&&_scrollController.offset == 60){
        setState(() {
          reachTop = false;
        });
      }
    });
    loadIndexData = FutureDio("get", Api.findIndexList, {
      "uid":SpUtil.sharedPreferences.getInt("uid")??1
    });
    _tabController = new TabController(length: 1, vsync: this,initialIndex: 0);
    super.initState();
  }

  void setIsFirstIn(){
      isFirstIn = false;
  }

  void setChange(int index,int comment,int applaud,int play,myApplaud,myFavor){
    setState(() {
      this.indexData[index]["comment"] = comment;
      this.indexData[index]["applaud"] = applaud;
      this.indexData[index]["play"] = play;
      this.indexData[index]["myApplaud"] = myApplaud;
      this.indexData[index]["myFavor"] = myFavor;
    });
  }

  @override
  void didUpdateWidget(covariant IndexPage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  Widget dragSpace(){
    return Container(
      height: 60,
      child: Row(
        children: [
          Spacer(),
          Icon(reachTop?Icons.refresh:Icons.arrow_downward,color: ProjectColor.deepColor,),
          Text(reachTop?"释放刷新":"下拉刷新",style: TextStyle(color: ProjectColor.deepColor,fontSize: 17),),
          Spacer(),
        ],
      ),
    );
  }


  Widget lastItem(bool isNoMore,int length){
    return Container(
      height: 30,
      margin: EdgeInsets.only(bottom: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(isNoMore||length==0?"没有更多啦":"加载中",style: TextStyle(
              fontSize: 15
          ),),
          isNoMore||length==0?SizedBox():LineSpinFadeLoaderIndicator(
            maxLineHeight: 6,
            minLineHeight: 6,
            radius: 13,
            maxLineWidth: 4,
          )
        ],
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        automaticallyImplyLeading: false,
        title: InkWell(
          onDoubleTap: (){
            _scrollController.jumpTo(60);
          },
          child: Container(
            width: 350,
            height: 50,
            padding: EdgeInsets.only(bottom: 15),
            alignment: Alignment.bottomLeft,
            child: Text("推荐",style: TextStyle(color: ProjectColor.deepColor,fontSize: 18),),
          ),
        ),
      ),
      backgroundColor: Colors.white,
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: (){
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Stack(
          children: [
            TabBarView(
                controller: _tabController,
                children: [
                  FutureBuilder(
                    future: loadIndexData,
                    builder: (BuildContext buildContext,AsyncSnapshot snapshot){
                      if(snapshot.connectionState == ConnectionState.done){
                        if(snapshot.hasError){
                          return Center(
                            child: Container(
                              width: 50,
                              height: 50,
                              child: LineSpinFadeLoaderIndicator(
                                ballColor: ProjectColor.mainColor,
                              ),
                            ),
                          );
                        }
                        indexData = snapshot.data.data["data"];
                        isLoading = false;
                        return NotificationListener<ScrollNotification>(
                          // 添加 NotificationListener 作为父容器
                          onNotification: (scrollNotification) {
                            if (scrollNotification.depth==0&&scrollNotification is ScrollStartNotification) {
                              setState(() {
                                isDragging = true;
                              });
                            }  else if (scrollNotification.depth==0&&scrollNotification is ScrollEndNotification) {
                              setState(() {
                                isDragging = false;
                                Future.delayed(Duration(milliseconds: 50),(){
                                  if(!isDragging&&_scrollController.offset<60) {
                                    if (_scrollController.offset == 0) {
                                      Future.delayed(
                                          Duration(milliseconds: 600), () {
                                        setState(() {
                                          if(!isLoading) {
                                            isLoading = true;
                                            loadIndexData = FutureDio(
                                                "get", Api.findIndexList, {
                                              "uid": SpUtil.sharedPreferences
                                                  .getInt("uid") ?? 1
                                            });
                                          }
                                        });
                                      });
                                    }
                                    _scrollController.animateTo(60,
                                        duration: Duration(milliseconds: 500),
                                        curve: Curves.ease);
                                  }
                                });
                              });
                            }
                            return true;
                          },
                          child:InViewNotifierList(
                              controller: _scrollController,
                              isInViewPortCondition: (double deltaTop,
                                  double deltaBottom, double vpHeight) {
                                return deltaTop < (0.5 * vpHeight) &&
                                    deltaBottom > (0.5 * vpHeight);
                              },
                              itemCount: indexData.length+3,
                              builder: (context,index){
                                return InViewNotifierWidget(
                                  id:"$index",
                                  builder: (BuildContext context,bool isInView,Widget child) {
                                    if (index == 0)
                                      return dragSpace();
                                    if (index == 1)
                                      return Container(
                                        height: 160,
                                        child: Swiper(
                                            itemCount: 3,
                                            autoplay: true,
                                            pagination: SwiperPagination(
                                                margin: EdgeInsets.only(
                                                    bottom: 20),
                                                builder: DotSwiperPaginationBuilder(
                                                    size: 5,
                                                    color: Colors.black12,
                                                    activeColor: ProjectColor
                                                        .deepColor,
                                                    activeSize: 5)),
                                            itemBuilder: (context, index) {
                                              return Container(
                                                height: 160,
                                                color: Colors.white,
                                                child: CachedNetworkImage(
                                                  imageUrl: imageList[index],
                                                  fit: BoxFit.cover,
                                                ),
                                              );
                                            }
                                        ),
                                      );
                                    else if (index == indexData.length + 2)
                                      return lastItem(false, 0);
                                    else {
                                      return IndexListItem(
                                        isInView: isInView,
                                        callBack: setIsFirstIn,
                                        isFirstIn: isFirstIn,
                                        data: indexData[index - 2],
                                        numChange: (comment, applaud, play,
                                            myApplaud, myFavor) =>
                                            setChange(
                                                index - 2, comment, applaud,
                                                play, myApplaud, myFavor),
                                      );
                                    }
                                  },);
                              }
                          ),
                        );
                      }else if(indexData.length==0)
                        return Center(
                          child: Container(
                            width: 50,
                            height: 50,
                            child: LineSpinFadeLoaderIndicator(
                              ballColor: ProjectColor.mainColor,
                            ),
                          ),
                        );
                      else return Stack(
                          children: [
                            NotificationListener<ScrollNotification>(
                              // 添加 NotificationListener 作为父容器
                              onNotification: (scrollNotification) {
                                if (scrollNotification.depth==0&&scrollNotification is ScrollStartNotification) {
                                  setState(() {
                                    isDragging = true;
                                  });
                                }  else if (scrollNotification.depth==0&&scrollNotification is ScrollEndNotification) {
                                  setState(() {
                                    isDragging = false;
                                    Future.delayed(Duration(milliseconds: 50),(){
                                      if(!isDragging&&_scrollController.offset<60) {
                                        if (_scrollController.offset == 0) {
                                          Future.delayed(
                                              Duration(milliseconds: 600), () {
                                            setState(() {
                                              if(!isLoading) {
                                                isLoading = true;
                                                loadIndexData = FutureDio(
                                                    "get", Api.findIndexList, {
                                                  "uid": SpUtil.sharedPreferences
                                                      .getInt("uid") ?? 1
                                                });
                                              }
                                            });
                                          });
                                        }
                                        _scrollController.animateTo(60,
                                            duration: Duration(milliseconds: 500),
                                            curve: Curves.ease);
                                      }
                                    });
                                  });
                                }
                                return true;
                              },
                              child:InViewNotifierList(
                                  controller: _scrollController,
                                  isInViewPortCondition: (double deltaTop,
                                      double deltaBottom, double vpHeight) {
                                    return deltaTop < (0.5 * vpHeight) &&
                                        deltaBottom > (0.5 * vpHeight);
                                  },
                                  itemCount: indexData.length+3,
                                  builder: (context,index){
                                    return InViewNotifierWidget(
                                      id:"$index",
                                      builder: (BuildContext context,bool isInView,Widget child) {
                                        if (index == 0)
                                          return dragSpace();
                                        if (index == 1)
                                          return Container(
                                            height: 160,
                                            child: Swiper(
                                                itemCount: 3,
                                                autoplay: true,
                                                pagination: SwiperPagination(
                                                    margin: EdgeInsets.only(
                                                        bottom: 20),
                                                    builder: DotSwiperPaginationBuilder(
                                                        size: 5,
                                                        color: Colors.black12,
                                                        activeColor: ProjectColor
                                                            .deepColor,
                                                        activeSize: 5)),
                                                itemBuilder: (context, index) {
                                                  return Container(
                                                    height: 160,
                                                    color: Colors.white,
                                                    child: CachedNetworkImage(
                                                      imageUrl: imageList[index],
                                                      fit: BoxFit.cover,
                                                    ),
                                                  );
                                                }
                                            ),
                                          );
                                        else if (index == indexData.length + 2)
                                          return lastItem(false, 0);
                                        else {
                                          return IndexListItem(
                                            isInView: isInView,
                                            callBack: setIsFirstIn,
                                            isFirstIn: isFirstIn,
                                            data: indexData[index - 2],
                                            numChange: (comment, applaud, play,
                                                myApplaud, myFavor) =>
                                                setChange(
                                                    index - 2, comment, applaud,
                                                    play, myApplaud, myFavor),
                                          );
                                        }
                                      },);
                                  }
                              ),
                            ),
                            Center(
                              child: Container(
                                width: 70,
                                height: 70,
                                decoration: BoxDecoration(
                                  color:Colors.black38,
                                  borderRadius: BorderRadius.all(Radius.circular(5)),
                                ),
                                alignment:Alignment.center,
                                child: Container(
                                  width: 50,
                                  height: 50,
                                  child: LineSpinFadeLoaderIndicator(
                                    ballColor: ProjectColor.mainColor,
                                  ),
                                ),
                              ),
                            )
                          ],
                        );
                    },
                  ),
                ]),
          ],
        ),
      )
    );
  }


}